<?php
class CategoryModel extends Models
{
	protected $tableName='category';

    public function getParentId($id)
    {
        if(!$current_category=$this->findByPk($id)) return false;
        return $current_category['parent_id'];
    }

    public function getRootCategories()
    {
        return $this->findAllByAttributes(array('parent_id'=>0));
    }

    public function getChildren($id=0)
    {
        if($children=$this->findAllByAttributes(array('parent_id'=>$id))){
            $model=$this->model->load('categoryDescriptionModel');
            foreach($children as $num=>$child){
                if($description=$model->findByPk($child['category_id'])){
                    $children[$num]['language_id']=$description['language_id'];
                    $children[$num]['name']=$description['name'];
                    $children[$num]['description']=$description['description'];
                    $children[$num]['meta_description']=$description['meta_description'];
                    $children[$num]['meta_keyword']=$description['meta_keyword'];
                    $children[$num]['seo_title']=$description['seo_title'];
                    $children[$num]['seo_h1']=$description['seo_h1'];
                }
            }
        }

        return $children;
    }

    public function getCategoriesNames($id=0)
    {
        $result=array();
        $categories=$id ? $this->findByPk($id) : $this->findAll();
        if($categories){
            if(sizeof($categories)==1) $categories=$this->getChildren();
            $categoryDescriptionModel=$this->model->load('categoryDescriptionModel');
            foreach($categories as $category){
                if($description=$categoryDescriptionModel->findByPk($category['category_id'])) $result[]=strtolower($description['name']);
            }
        }
        return $result;
    }

    public function getCategoriesRootTree()
    {
        $children=array();
        if($rootCategories=$this->getRootCategories()){
            foreach($rootCategories as $category){
                $children[$category['category_id']]=$this->getChildren($category['category_id']);
            }
        }

        return $children;
    }

    public function getTableName(){
        return $this->tableName;
    }
}